<template>
  <div style="padding: 20px 0">
    <el-tree ref="refUnitTree" node-key="id" @check="checkChange"
             @node-click="unitSelectChange" :indent="5"
             :expand-on-click-node="false" :default-expanded-keys="defaultExpand"
             show-checkbox check-strictly highlight-current
             :data="unitTree" :props="defaultProps">
      <template v-slot="{node}">
        <el-text :title="node.label" truncated>
          {{ node.label }}
        </el-text>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import {shallowRef, toRaw, unref} from 'vue';
import {getAction} from '@/request/BaseRequest';
import {isEmpty, listToTrees, real} from '@/utils/CommonUtils';

const defaultExpand = shallowRef(['rootNode']);
const unitTree = shallowRef([]);
const refUnitTree = shallowRef();
const loading = shallowRef(false);
const emits = defineEmits(['selectChange']);
const defaultProps = {
  children: 'children',
  label: 'unitName',
};


function reload() {
  return new Promise((success, err) => {
    loading.value = true;
    getAction('/sys/unit/loadUnits').then(data => {
      loading.value = false;
      if (data.success) {
        let result = data.result;
        setUnitTree(result);
        success();
      }
    });
  });
}

function setUnitTree(list) {
  if (isEmpty(list)) list = [];
  let rootNode = createRootNode();
  rootNode.children = listToTrees(list);
  resolveDefaultExpands([rootNode]);
  unitTree.value = [rootNode];
}

function resolveDefaultExpands(list) {
  let res = [];
  list.forEach(node => {
    res.push(node.id);
    let children = node.children;
    if (isEmpty(children)) return;
    children.forEach(c => {
      res.push(c.id);
      let childrenChildren = c.children;
      if (isEmpty(childrenChildren)) return;
      childrenChildren.forEach(cc => {
        res.push(cc.id);
      });
    });
  });
  defaultExpand.value = res;
}

function createRootNode() {
  return {
    id: 'rootNode',
    unitName: '组织结构部署',
    children: []
  };
}

function checkChange(data) {
  let node = refUnitTree.value.getCheckedNodes();
  if (isEmpty(node)) {
    emits('selectChange', undefined);
  } else {
    refUnitTree.value.setCheckedKeys([data.id]);
    emits('selectChange', node);
  }
}

function unitSelectChange(node) {
  if (isEmpty(node)) {
    refUnitTree.value.setCheckedKeys([]);
    return;
  }
  node = real(node);
  refUnitTree.value.setCheckedKeys([node.id]);
  emits('selectChange', node);
}

function clearSelect() {
  refUnitTree.value.setCheckedKeys([]);
}

defineExpose({
  unitSelectChange,
  clearSelect,
  reload
});
</script>
